/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.bsly.modules.app.controller;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.bsly.common.utils.HttpUtil;
import io.bsly.common.utils.R;
import io.bsly.common.utils.RedisTools;
import io.bsly.modules.platform.api.douDianApi.AccessTokenVo;
import io.bsly.modules.app.annotation.JwtIgnore;
import io.bsly.modules.app.entity.localEntity.UserEntity;
import io.bsly.modules.app.pojo.DyLoginForm;
import io.bsly.modules.app.pojo.LoginForm;
import io.bsly.modules.app.pojo.RegisterForm;
import io.bsly.modules.app.service.localmaster.SysCaptchaService;
import io.bsly.modules.app.service.localmaster.UserService;
import io.bsly.common.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.io.IOUtils;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api(tags = "登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private @Qualifier("redistools")  RedisTools redisTools;

    @Value("${appid}")
    private String appid;
    @Value("${appsecret}")
    private String appsecret;

    private String jscode2sessionUrl ="https://developer.toutiao.com/api/apps/v2/jscode2session";
    @JwtIgnore
    @ApiOperation("小程序获取信息")
    @GetMapping("code2Session")
    public R code2Session(String code,String anonymousCode){
        Map map = new HashMap();
        map.put("appid",appid);
        map.put("secret",appsecret);
        if (!StringUtils.isEmpty(code))
         map.put("code",code);
        if (!StringUtils.isEmpty(anonymousCode))
         map.put("anonymous_code",anonymousCode);

        String s = JSON.toJSONString(map);
        HttpUtil.ResponseData responseData = HttpUtil.post(jscode2sessionUrl, s);
        String data = responseData.getData();
        JSONObject jsonObject = new JSONObject(data);
        System.out.println(data);
        if ("success".equals(jsonObject.get("err_tips").toString())){
            Object data1 = jsonObject.get("data");
            return R.ok().put("data",data1);
        }else {
            return R.error(jsonObject.toString());
        }
    }

    /**
     * 验证码
     */
    @JwtIgnore
    @GetMapping("captcha.jpg")
    @ApiOperation("图形验证码")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @JwtIgnore
    @PostMapping("register")
    @ApiOperation(value = "通用注册（用户名密码）" )
    public R register(@RequestBody @Validated RegisterForm form){
        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getUsername());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        userService.save(user);
        return R.ok();
    }

    /**
     * 登录
     */
    @JwtIgnore
    @PostMapping("login")
    @ApiOperation("通用登录")
    public R login(@RequestBody @Valid LoginForm form){
        //用户登录
        long userId = userService.login(form);
        //生成token
        String token = jwtUtils.generateToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);//jwt token subject 为id
        map.put("expire", jwtUtils.getExpire());
        map.put("userId",userId);
        return R.ok(map);
    }


    /**
     * 抖音登录与注册
     */
    @JwtIgnore
    @PostMapping("dylogin")
    @ApiOperation("抖音openid进行登录或注册")
    public R dyloginOrRegister(@RequestBody @Valid DyLoginForm form){
        //用户登录
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getOpenid, form.getOpenid()));
        if (Objects.isNull(userEntity)){
            userEntity=new UserEntity();
            BeanUtils.copyProperties(form,userEntity);
            userEntity.setCreateTime(new Date());
            userService.save(userEntity);
        }
        //生成token
        String token = jwtUtils.generateToken(userEntity.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);//jwt token subject 为id
        map.put("expire", jwtUtils.getExpire());
        map.put("userId",userEntity.getId());
        map.put("status",userEntity.getStatus());



        return R.ok(map);
    }

}
